package cn.sdormitory.evaluation.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.sdormitory.common.exception.ApiException;
import cn.sdormitory.common.utils.DataRoleUtil;
import cn.sdormitory.common.utils.SysUserUtils;
import cn.sdormitory.evaluation.dao.WorkDayDao;
import cn.sdormitory.evaluation.dao.WorkStuCheckDao;
import cn.sdormitory.evaluation.entity.WorkDayEntity;
import cn.sdormitory.evaluation.entity.WorkStuCheckEntity;
import cn.sdormitory.evaluation.service.WorkDayService;
import cn.sdormitory.evaluation.vo.WorkDayVO;
import cn.sdormitory.exam.vo.ExamInfoVO;
import cn.sdormitory.school.entity.SchoolDuty;
import cn.sdormitory.sys.dao.SysDeptDao;
import cn.sdormitory.sys.dao.SysUserDao;
import cn.sdormitory.sys.entity.SysDept;
import cn.sdormitory.sys.entity.SysUser;
import cn.sdormitory.sys.service.SysUserRoleService;
import cn.sdormitory.sys.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
public class WorkDayServiceImpl extends ServiceImpl<WorkDayDao, WorkDayEntity> implements WorkDayService {

    @Resource
    WorkStuCheckDao workStuCheckDao;
    @Resource
    WorkDayDao workDayDao;
    @Resource
    DataRoleUtil dataRoleUtil;

    @Override
    public IPage<WorkDayEntity> findWorkDayPageList(WorkDayEntity vo) {
        LambdaQueryWrapper<WorkDayEntity> wrapper = new LambdaQueryWrapper<>();
        //获取查询当前用户能查询到的范围
        List<String> userNameList = dataRoleUtil.getDeptSubordinateUserList();
        wrapper.in(userNameList.size()>0,WorkDayEntity::getRegistrant,userNameList);
        //任务日期
        wrapper.eq(!StringUtils.isEmpty(vo.getTaskDate()),WorkDayEntity::getTaskDate,vo.getTaskDate());
        //班级
        wrapper.eq(!StringUtils.isEmpty(vo.getClassId()),WorkDayEntity::getClassId,vo.getClassId());
        if("0".equals(vo.getDone())){//未登记
            wrapper.isNull(WorkDayEntity::getKnowledgePoints);
            wrapper.isNull(WorkDayEntity::getSchoolAsignment);
            wrapper.isNull(WorkDayEntity::getSyntax);
            wrapper.isNull(WorkDayEntity::getWord);
        }
        if("1".equals(vo.getDone())){//已登记
            wrapper.nested(new Consumer<LambdaQueryWrapper<WorkDayEntity>>() {
                @Override
                public void accept(LambdaQueryWrapper<WorkDayEntity> orWrapper) {
                    orWrapper.isNotNull(WorkDayEntity::getKnowledgePoints).or();
                    orWrapper.isNotNull(WorkDayEntity::getSchoolAsignment).or();
                    orWrapper.isNotNull(WorkDayEntity::getSyntax).or();
                    orWrapper.isNotNull(WorkDayEntity::getWord).or();
                }
            });
        }

        wrapper.orderBy(true,false,WorkDayEntity::getCreatedTime);
        Page<WorkDayEntity> page = page(new Page<>(vo.getPageNum(), vo.getPageSize()), wrapper);
        List<WorkDayEntity> records = page.getRecords();
        for (WorkDayEntity record : records) {
            List<Map<String, String>> maps = workDayDao.selectCountRaio(record.getId());
            List<String> list1 = new ArrayList<>();
            List<String> list2 = new ArrayList<>();
            for (Map<String, String> map : maps) {

                String done_num = String.valueOf(map.get("done_num")) ;
                String count = String.valueOf(map.get("count"));
                String check_type = String.valueOf(map.get("check_type"));
                String stuCount = String.valueOf(map.get("stuCount"));
                if("1".equals(check_type)){
                    BigDecimal rounded = new BigDecimal(count).divide(new BigDecimal(stuCount),2, RoundingMode.HALF_UP);
//                    BigDecimal bigDecimal = rounded.setScale(2, RoundingMode.HALF_UP);
                    list1.add("第"+done_num+"次通过率：" + rounded.multiply(new BigDecimal(100)));
                }
                if("2".equals(check_type)){
                    BigDecimal rounded = new BigDecimal(count).divide(new BigDecimal(stuCount),2, RoundingMode.HALF_UP);
//                    BigDecimal bigDecimal = rounded.setScale(2, RoundingMode.HALF_UP);
                    list2.add("第"+done_num+"次通过率：" + rounded.multiply(new BigDecimal(100)));
                }
            }
            record.setRecitePassRatioList(list1);
            record.setWorkCheckRatioList(list2);


        }
        return page;
    }

    @Override
    public List<WorkStuCheckEntity> studentListByType(WorkStuCheckEntity vo) {
        LambdaQueryWrapper<WorkStuCheckEntity> lw = new LambdaQueryWrapper<>();
        lw.eq(WorkStuCheckEntity::getCheckType,vo.getCheckType());
        lw.eq(WorkStuCheckEntity::getWorkDayId,vo.getWorkDayId());
        lw.orderByDesc(WorkStuCheckEntity::getStudentId);
        List<WorkStuCheckEntity> workStuCheckEntities = workStuCheckDao.selectList(lw);
        return workStuCheckEntities;
    }

    @Override
    public WorkDayEntity getDetailById(Long id) {
        //查询每日工作
        WorkDayEntity workDayEntity = this.baseMapper.selectById(id);
        if(workDayEntity==null){
            throw new ApiException("查询不到数据");
        }
//        Long userId = SysUserUtils.getSysUser().getId();
//        if(userId!=workDayEntity.getRegistrant()){
//            throw new ApiException("你没有权限查看");
//        }
        //查询学生列表
        //背诵
        WorkStuCheckEntity recite=new WorkStuCheckEntity();
        recite.setCheckType("1");
        recite.setWorkDayId(id);
        List<WorkStuCheckEntity> reciteStuCheckEntities = this.studentListByType(recite);
        workDayEntity.setReciteStudentList(reciteStuCheckEntities);
        //作业检查
        WorkStuCheckEntity work=new WorkStuCheckEntity();
        work.setCheckType("2");
        work.setWorkDayId(id);
        List<WorkStuCheckEntity> workStuCheckEntities = this.studentListByType(work);
        workDayEntity.setWorkStudentList(workStuCheckEntities);
        return workDayEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDetailById(WorkDayEntity vo) {
        String today = DateUtil.today();
        if(!today.equals(vo.getTaskDate())){
            throw new ApiException("只能提交今日任务");
        }
        //背诵情况
        List<WorkStuCheckEntity> reciteStudentList = vo.getReciteStudentList();
        //作业检查情况
        List<WorkStuCheckEntity> workStudentList = vo.getWorkStudentList();
        vo.setModifyBy(SysUserUtils.getSysUser().getUsername());
        vo.setModifyTime(new Date());
        StringBuffer sb = checkRegistrantDesc(vo, reciteStudentList, workStudentList);

        vo.setRegistrantDesc(sb.toString());
        int i = this.baseMapper.updateById(vo);
        //批量修改背诵情况
        //workStuCheckDao.batchUpdate(reciteStudentList);
        //批量修改作业检查情况
        //workStuCheckDao.batchUpdate(workStudentList);
        return i;
    }

    @NotNull
    private StringBuffer checkRegistrantDesc(WorkDayEntity vo, List<WorkStuCheckEntity> reciteStudentList, List<WorkStuCheckEntity> workStudentList) {
        StringBuffer sb = new StringBuffer();
        if(StringUtils.isEmpty(vo.getKnowledgePoints())){
            sb.append("重要知识点没有登记").append("\n");
        }
        if(StringUtils.isEmpty(vo.getSyntax())){
            sb.append("语法没有登记").append("\n");
        }
        if(StringUtils.isEmpty(vo.getWord())){
            sb.append("单词没有登记").append("\n");
        }
        if(StringUtils.isEmpty(vo.getSchoolAsignment())){
            sb.append("作业没有登记").append("\n");
        }

        return sb;
    }

    @Override
    public int addCheckResult(List<WorkStuCheckEntity> vo) {
        for (WorkStuCheckEntity workStuCheckEntity : vo) {
            if("0".equals(workStuCheckEntity.getCheckState())){
                throw  new ApiException("未完成的学生不能提交");
            }
            workStuCheckEntity.setCreateBy(SysUserUtils.getSysUser().getUsername());
            workStuCheckEntity.setCreatedTime(new Date());
        }
        int i = workStuCheckDao.batchaAdd(vo);
        return i;
    }




}
